package com.yanqu.road.server.gameplayer.module.activity.taobao;

import com.alibaba.fastjson.JSON;
import com.yanqu.road.dao.impl.taobao.UserTaoBaoDataDaoImpl;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.enums.eTaoBaoStatusEnum;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.pb.taobao.TaoBao;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.VipMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.newyearbag.NewYearBagMgr;
import com.yanqu.road.server.manger.activity.taobao.TaoBaoMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import taobao.TaoBaoItem;
import taobao.TaoBaoLabel;
import taobao.UserTaoBaoData;
import taobao.config.TaoBaoItemConfig;
import taobao.config.TaoBaoLabelConfig;
import taobao.config.TaoBaoPriceStatusConfig;

import java.util.ArrayList;

public class TaoBaoModule extends GeneralModule {

    private UserTaoBaoData userTaoBaoData;

    public TaoBaoModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
        int openActivityId = TaoBaoMgr.getOpenActivityId();
        if (openActivityId > 0) {
            userTaoBaoData = new UserTaoBaoDataDaoImpl().getUserTaoBaoData(openActivityId, getUserId());
            if (userTaoBaoData == null) {
                init();
            }
        }
        return true;
    }

    @Override
    public void afterLogin() {
        init();

        // 2023年1月23日热更修复淘宝亏本没触发成就，2023-01-30 00:00:00前有效
        if (System.currentTimeMillis() < 1675008000000L) {
            if (userTaoBaoData != null && userTaoBaoData.getDealStatus() == eTaoBaoStatusEnum.DEAL.getValue() && userTaoBaoData.getEarnPrice() <= 0) {
                if (ActivityMgr.activityInTime(NewYearBagMgr.getActivityInfo())) {
                    player.notifyListener(eGamePlayerEventType.TaoBaoTimes.getValue(), 1);
                }
            }
        }
    }

    private void syncDataMsg() {
        if (userTaoBaoData != null && userTaoBaoData.getItemId() > 0) {
            TaoBao.TaoBaoDataMsg.Builder syncMsg = getTaobaoDataMsg();
            player.sendPacket(ClientProtocol.U_SYNC_TAOBAO_DATA, syncMsg);
        }
    }

    private TaoBao.TaoBaoDataMsg.Builder getTaobaoDataMsg() {
        TaoBao.TaoBaoDataMsg.Builder syncMsg = TaoBao.TaoBaoDataMsg.newBuilder();
        syncMsg.setItemId(userTaoBaoData.getItemId());
        syncMsg.setInitPrice(userTaoBaoData.getInitPrice());
        for (TaoBaoLabel label : userTaoBaoData.getLabelList()) {
            TaoBao.TaoBaoLabelMsg.Builder msg = TaoBao.TaoBaoLabelMsg.newBuilder();
            msg.setId(label.getId());
            msg.setSurface(label.getSurface());
            msg.setX(label.getX());
            msg.setY(label.getY());
            syncMsg.addLabel(msg);
        }
        syncMsg.setPlay(userTaoBaoData.getPlayStatus());
        syncMsg.addAllSelectedLabel(userTaoBaoData.getSelectedLabelList());
        syncMsg.addAllPriceFluctuation(userTaoBaoData.getPriceFluctuationList());
        syncMsg.setStatus(userTaoBaoData.getDealStatus());
        if (isOverSelectTimes(userTaoBaoData)) {
            TaoBao.TaoBaoResultMsg.Builder result = TaoBao.TaoBaoResultMsg.newBuilder();
            result.setLastPrice(getLastPrice());
            result.setEvaluate(getEvaluate());
            syncMsg.setResult(result);
        }
        return syncMsg;
    }

    private void syncActivityConfigMsg() {
        TaoBao.SyncTaoBaoConfigMsg.Builder syncMsg = TaoBao.SyncTaoBaoConfigMsg.newBuilder();
        for (TaoBaoItemConfig config : TaoBaoMgr.getTaoBaoItemConfigMap().values()) {
            TaoBao.TaoBaoItemConfigMsg.Builder itemMsg = TaoBao.TaoBaoItemConfigMsg.newBuilder();
            itemMsg.setItemId(config.getItemId());
            itemMsg.setType(config.getType());
            itemMsg.setIcon(config.getIcon());
            itemMsg.setSellNpc(config.getSellNpc());
            itemMsg.setSurface(config.getFaceNumMap().size());
            String posNpc = config.getPosNpc();
            if (posNpc != null) {
                itemMsg.setPosNpc(posNpc);
            }
            syncMsg.addItemConfig(itemMsg);
        }
        for (TaoBaoLabelConfig config : TaoBaoMgr.getTaoBaoLabelConfigMap().values()) {
            TaoBao.TaoBaoLabelConfigMsg.Builder msg = TaoBao.TaoBaoLabelConfigMsg.newBuilder();
            msg.setLabelId(config.getTagId());
            msg.setType(config.getType());
            msg.setIcon(config.getIcon());
            syncMsg.addLabelConfig(msg);
        }
        player.sendPacket(ClientProtocol.U_SYNC_TAOBAO_CONFIG, syncMsg);
    }

    private void initTaoBaoData(int activityId) {
        if (userTaoBaoData == null || userTaoBaoData.getActivityId() != activityId) {
            userTaoBaoData = new UserTaoBaoData();
            userTaoBaoData.setActivityId(activityId);
            userTaoBaoData.setUserId(getUserId());
            reset();
            userTaoBaoData.setInsertOption();
        }else {
            reset();
        }
    }

    /**
     * 重置
     * @param userTaoBaoData
     */
    private void resetTaoBaoData(UserTaoBaoData userTaoBaoData) {
        log.info("before user {} reset taobaoData: {}", getUserId(), JSON.toJSONString(userTaoBaoData));
        TaoBaoItem taoBaoItem = TaoBaoMgr.randomTaoBaoItem(VipMgr.getVipLv(player.getUserInfo().getVipExp()),userTaoBaoData.getItemId() == 0);
        userTaoBaoData.setItemId(taoBaoItem.getItemId());
        userTaoBaoData.setInitPrice(taoBaoItem.getInitPrice());
        userTaoBaoData.setLabelList(taoBaoItem.getLabels());
        userTaoBaoData.setSelectedLabelList(new ArrayList<>());
        userTaoBaoData.setPriceFluctuationList(new ArrayList<>());
        userTaoBaoData.setResetTime(System.currentTimeMillis());
        userTaoBaoData.setPriceStatus("");
        userTaoBaoData.setDealStatus(eTaoBaoStatusEnum.NORMAL.getValue());
        userTaoBaoData.setEarnPrice(0);
        userTaoBaoData.setPlayStatus(0);

        log.info("after user {} reset taobaoData: {}", getUserId(), JSON.toJSONString(userTaoBaoData));
    }

    public int bargain(int labelIndex) {

        if (labelIndex >= userTaoBaoData.getLabelList().size()) {
            //超出长度 异常
            return GameErrorCode.E_TAOBAO_ERROR_LABEL;
        }

        if (userTaoBaoData.getSelectedLabelList().contains(labelIndex)) {
            //已选
            return GameErrorCode.E_TAOBAO_LABEL_SELECTED;
        }

        if (!TaoBaoMgr.isActivityOpen()) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }

        if (isOverSelectTimes(userTaoBaoData)) {
            return GameErrorCode.E_TAOBAO_LABEL_SELECTED_MAX_NUM;
        }

        TaoBaoLabel label = userTaoBaoData.getLabelList().get(labelIndex);
        int labelEffect = TaoBaoMgr.getLabelEffect(label.getId());
        userTaoBaoData.addBargain(labelIndex, labelEffect);
        if (isOverSelectTimes(userTaoBaoData)) {
            //表示结束了 处理下
            settlement(userTaoBaoData);
        }
        TaoBao.TaoBaoBargainRespMsg.Builder msg = TaoBao.TaoBaoBargainRespMsg.newBuilder();
        msg.setRet(0);
        msg.setPriceFluctuation(labelEffect);
        msg.setData(getTaobaoDataMsg());
        player.sendPacket(ClientProtocol.U_TAOBAO_BARGAIN, msg);
        return 0;
    }

    private void settlement(UserTaoBaoData userTaoBaoData) {
        int finalPrice = getFinalPrice();
        TaoBaoPriceStatusConfig statusConfig = TaoBaoMgr.getPriceStatusByFluctuation(userTaoBaoData.getTotalFluctuation());
        int earnRate = TaoBaoMgr.getEarnPrice(statusConfig);
        int earnPrice = (int)(finalPrice * (1000 + earnRate) / 1000.0) - finalPrice;
        userTaoBaoData.setPriceStatus(statusConfig.getIcon());
        userTaoBaoData.setEarnPrice(earnPrice);
        if (earnPrice <= 0) {
            userTaoBaoData.setDealStatus(eTaoBaoStatusEnum.DEAL.getValue());

            // 成就任务
            player.notifyListener(eGamePlayerEventType.TaoBaoTimes.getValue(), 1);
        }

    }

    private boolean isOverSelectTimes(UserTaoBaoData data) {
        return data.getSelectedLabelList().size() >= Math.min(data.getLabelList().size(), TaoBaoMgr.getBargainTimes());
    }

    public int deal() {
        if (!TaoBaoMgr.isActivityOpen()) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }
        if (!isOverSelectTimes(userTaoBaoData)) {
            return GameErrorCode.E_TAOBAO_LABEL_SELECTED_NO_ENOUGH;
        }

        if (userTaoBaoData.getDealStatus() != eTaoBaoStatusEnum.NORMAL.getValue()) {
            return GameErrorCode.E_TAOBAO_DEAL_ALREADY;
        }

        userTaoBaoData.setDealStatus(eTaoBaoStatusEnum.DEAL.getValue());
        TaoBao.TaoBaoDealRespMsg.Builder msg = TaoBao.TaoBaoDealRespMsg.newBuilder();
        msg.setRet(0);
        int earnPrice = userTaoBaoData.getEarnPrice();
        String reward = GameConfig.GAME_MONEY_INGOTS + "=" + earnPrice;
        msg.setReward(reward);
        player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.Activity, eLogMoneyType.TaboBao);
        player.sendPacket(ClientProtocol.U_TAOBAO_DEAL, msg);
        syncDataMsg();

        // 成就任务
        player.notifyListener(eGamePlayerEventType.TaoBaoTimes.getValue(), 1);

        return 0;
    }

    private int getLastPrice() {
        int finalPrice = getFinalPrice();
        return finalPrice + userTaoBaoData.getEarnPrice();
    }

    private int getFinalPrice() {
        int changePrice = 0;
        for (Integer fluctuation : userTaoBaoData.getPriceFluctuationList()) {
            changePrice += (int) Math.ceil(userTaoBaoData.getInitPrice() * fluctuation / 1000.0);
        }
        return changePrice + + userTaoBaoData.getInitPrice();
    }

    private String getEvaluate() {
        return userTaoBaoData.getPriceStatus();
    }

    public void giveUp() {
        if (userTaoBaoData != null) {
            userTaoBaoData.setDealStatus(eTaoBaoStatusEnum.GIVE_UP.getValue());
        }
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        if (userTaoBaoData != null) {
            if (userTaoBaoData.isInsertOption()) {
                new UserTaoBaoDataDaoImpl().add(userTaoBaoData);
            } else if (userTaoBaoData.isUpdateOption()) {
                new UserTaoBaoDataDaoImpl().update(userTaoBaoData);
            }
        }
        return true;
    }

    public void play() {
        userTaoBaoData.setPlayStatus(1);
        syncDataMsg();
    }

    public void init() {
        int openActivityId = TaoBaoMgr.getOpenActivityId();
        if (openActivityId > 0 && SystemOpenMgr.systemOpen(player, eSystemId.TaoBao.getValue())) {
            syncActivityConfigMsg();
            initTaoBaoData(openActivityId);
            syncDataMsg();
        }
    }

    public void notifyReset() {
        reset();
    }

    private void reset() {
        synchronized (this) {
            if (userTaoBaoData == null) {
                return;
            }
            if (TaoBaoMgr.needReset(userTaoBaoData.getResetTime())) {
                resetTaoBaoData(userTaoBaoData);
                syncDataMsg();
            }
        }
    }
}
